package cn.iocoder.springboot.lab72;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.sql.*;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;

public class JdbcBenchmark {

    @Benchmark
    public void testConnection() {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("db_config");
        String username = resourceBundle.getString("username");
        String password = resourceBundle.getString("password");
        String url = resourceBundle.getString("url");
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static void main(String[] args) throws RunnerException {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("db_config");
        int forks = Integer.parseInt(resourceBundle.getString("forks"));
        int threads = Integer.parseInt(resourceBundle.getString("threads"));
        int warmupIterations = Integer.parseInt(resourceBundle.getString("warmup.iterations"));
        int warmupTime = Integer.parseInt(resourceBundle.getString("warmup.time"));
        int measurementIterations = Integer.parseInt(resourceBundle.getString("measurement.iterations"));
        int measurementTime = Integer.parseInt(resourceBundle.getString("measurement.time"));
        String filepath = resourceBundle.getString("filepath");
        Options option = new OptionsBuilder()
                .include(JdbcBenchmark.class.getSimpleName())
                .result(filepath)
                .resultFormat(ResultFormatType.TEXT)
                .forks(forks)
                .threads(threads)
                .mode(Mode.All)
                .timeUnit(TimeUnit.MILLISECONDS)
                .warmupIterations(warmupIterations)
                .warmupTime(TimeValue.seconds(warmupTime))
                .measurementIterations(measurementIterations)
                .measurementTime(TimeValue.seconds(measurementTime))
                .build();
        new Runner(option).run();
    }

}
